<template>
  <!-- 公式配置 -->
  <div class="app-container">

    <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="游戏" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in gameListAll" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="公式名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="公式名称"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button> -->
      </el-form-item>
    </el-form>

    <div class="table_box">
      <el-table v-loading="loading" :data="equationList">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column label="序号" prop="id" width="80" />
        <el-table-column label="游戏" prop="gameName"></el-table-column>
        <el-table-column label="公式名称" prop="name"></el-table-column>
        <el-table-column label="公式" prop="formul" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 添加或修改公式配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form class="gongshi_form" ref="form" :inline="true" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="游戏" prop="gameId">
          <el-select v-model="form.gameId" @change="selectType" placeholder="请选择游戏" :disabled="form.id != null">
            <el-option v-for="dict in gameListAll" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公式名称" prop="name">
          <el-input style="width:217px" v-model="form.name" type="text" placeholder="请输入公式名称" />
        </el-form-item>
        <br />
        <el-form-item label="可选属性" prop="formul">
          <template>
            <div class="type_box" v-if="attrNumber&&attrNumber.length">
              <div class="attrhead">数值型</div>
              <div class="kexuan-box flex">
                <div class="attr_item" v-for="(checkItem,checkIndex) in attrNumber" :key="checkIndex" @click="changedfn(checkItem)"> {{checkItem.fieldName}} </div>
              </div>
            </div>
            <div class="type_box" v-if="attrRadio&&attrRadio.length">
              <div class="attrhead">单选型</div>
              <div class="kexuan-box flex">
                <div class="attr_item" v-for="(checkItem,checkIndex) in attrRadio" :key="checkIndex" @click="changedfn(checkItem)"> {{checkItem.fieldName}} </div>
              </div>
            </div>
            <div class="type_box" v-if="attrCheckbox&&attrCheckbox.length">
              <div class="attrhead">多选型</div>
              <div class="kexuan-box flex">
                <div class="attr_item" v-for="(checkItem,checkIndex) in attrCheckbox" :key="checkIndex" @click="changedfn(checkItem)"> {{checkItem.fieldName}} </div>
              </div>
            </div>
            <div class="type_box" v-if="attrBoxradio&&attrBoxradio.length">
              <div class="attrhead">多选&gt;单选</div>
              <div class="kexuan-box flex">
                <div class="attr_item" v-for="(checkItem,checkIndex) in attrBoxradio" :key="checkIndex" @click="changedfn(checkItem)"> {{checkItem.fieldName}} </div>
              </div>
            </div>

            <!-- <div class="kexuan-box flex" v-if="selectEquas&&selectEquas.length">
              <div class="attr_item" v-for="(checkItem,checkIndex) in selectEquas" :key="checkIndex" @click="changedfn(checkItem)"> {{checkItem.fieldName}} </div>
            </div>
            <div v-else>
              请先选择游戏
            </div> -->
            <div style="width:500px" v-if="!selectEquas||selectEquas.length==0">
              请先选择游戏
            </div>

          </template>

        </el-form-item><br />

        <el-form-item label="运算符号" prop="">
          <div style="width:500px">
            <el-button type="primary" @click="yunsuanfu('+')"> + </el-button>
            <el-button type="primary" @click="yunsuanfu('-')"> - </el-button>
            <el-button type="primary" @click="yunsuanfu('*')"> × </el-button>
            <el-button type="primary" @click="yunsuanfu('/')"> ÷ </el-button>
            <el-button type="primary" @click="yunsuanfu('(')"> ( </el-button>
            <el-button type="primary" @click="yunsuanfu(')')"> ) </el-button>
            <el-button type="danger" @click="yunsuanfu('del')"> <i class="el-icon-back"></i> </el-button>
          </div>
        </el-form-item><br />
        <el-form-item label="公式" prop="formul">
          <el-input style="width:600px" ref="formulRef" v-model="form.formul" type="textarea" :rows="3" placeholder="请输入内容" />

        </el-form-item><br />
        <el-form-item label="区服系数" prop="">
          <template>
            <div class="tip" style="color:red">
              区服系数配置后，系统计算价格时，会将公式计算结果乘以配置的区服系数作为最终结果。<br />
              如果不需要折价或者加价的区服可不配置区服系数。
            </div>
            <div class="qufu_box">
              <!--区服系数配置 -->
              <div class="flex head">
                <div class="tit" v-if="form.gameType==0">系统</div>
                <div class="tit" v-if="form.gameType==0">运营商</div>
                <div class="tit">大区</div>
                <div class="tit">服务器</div>
                <div class="tit">区服系数</div>
                <div class="tit" style="width:100px;flex-shrink:0">操作</div>
              </div>
              <div class="qufu_item flex" v-for="(item,i) in qufuPeizhi" :key="i">
                <el-select v-if="form.gameType==0" v-model="item.systemName" filterable clearable placeholder="请选择系统" @change="changeSystem($event,item)">
                  <el-option v-for="item in systemList" :key="item.id" :label="item.fieldName" :value="item.fieldName" />
                </el-select>
                <el-select v-if="form.gameType==0" @change="getAreaList($event,item)" v-model="item.carrierName" filterable clearable placeholder="请选择运营商">
                  <el-option v-for="item in carrierList" :key="item.id" :label="item.fieldName" :value="item.fieldName" />
                </el-select>
                <el-select v-model="item.groupName" filterable clearable placeholder="请选择大区" @change="changefn($event,item)">
                  <el-option v-for="item in groupList" :key="item.id" :label="item.fieldName" :value="item.fieldName" />
                </el-select>
                <el-select v-model="item.serverName" filterable clearable placeholder="请选择服务器" @change="changeServe($event,item)">
                  <el-option v-for="item in serverList" :key="item.id" :label="item.fieldName" :value="item.fieldName" />
                </el-select>
                <el-input-number v-model="item.num" :step="0.1" :min="0" :max="9999" :precision="2" placeholder="请输入系数" />
                <div class="move">
                  <i class="el-icon-error" @click="moveQufu(i)"></i>
                </div>
              </div>
              <div class="add_btn">
                <el-button @click="addQufu" style="width:120px" type="primary" plain><i class="el-icon-plus"></i></el-button>
              </div>

            </div>
          </template>

        </el-form-item><br />
        <el-form-item label="备注" prop="remark">
          <el-input style="width:600px" v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="注意" prop="remark">
          <span style="color:red">公式中的填充项必须与配置游戏属性的一级分类对应。否则估值不准</span>
        </el-form-item> -->
      </el-form>
      <div  class="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAppEquationList,
  tenantFormulaSettingsList,
  tenantFormulaSettingsAdd,
  tenantFormulaSettingsEdit,
  tenantFormulaSettingsDel,
} from "@/api/equation/equation";
import gameDictionaryApi from "@/api/gameConfig/gameDictionary";

import gameListApi from "@/api/gameConfig/gameList";

export default {
  name: "",
  data() {
    return {
      youxiId: null,
      youxiname: "",
      youxishuname: "",
      serverOpen: false,
      typed: "",
      copyVlaue: "",
      selectEquas: [],

      attrNumber: [],
      attrRadio: [],
      attrCheckbox: [],
      attrBoxradio: [],

      radio: 1,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公式配置表格数据
      equationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
      },
      // 表单参数
      form: {
        formul: "",
        name: "",
        gameId: "",
        gameName: "",
        serverRegion: "",
        remark: "",
      },
      formServe: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        formul: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      systemList: [], //系统
      carrierList: [], //运营商
      groupList: [], //大区
      serverList: [], //服务器
      gameListAll: [],

      qufuPeizhi: [
        // {
        //   systemId: "",
        //   carrierId: "",
        //   groupId: "",
        //   serverId: "",
        //   num: 1,
        // },
      ],
    };
  },
  created() {
    this.getList();
    this.gamelistAlls();
  },
  methods: {
    // 增加一条区服配置
    addQufu() {
      this.qufuPeizhi.push({
        systemId: "",
        carrierId: "",
        groupId: "",
        serverId: "",
        systemName: "",
        carrierName: "",
        groupName: "",
        serverName: "",
        num: 1,
      });
      if(this.form.gameType==1){
        this.serverList = []
      }else{
        this.groupList = []
        this.serverList = []
        
      }
    },
    // 移除一条区服配置
    moveQufu(i) {
      this.qufuPeizhi.splice(i, 1);
    },
    async gamelistAlls() {
      const res = await gameListApi.getGameList();
      // console.log(res);
      this.gameListAll = res.rows;
    },

    //点击属性
    changedfn(item) {
      console.log("%c Line:272 🍢 item", "color:#7f2b82", item);
      this.form.formul = this.form.formul + item.fieldName;
      this.$refs.formulRef.focus();
    },
    // 点击运算符
    yunsuanfu(val) {
      if (val == "del") {
        this.form.formul = this.form.formul.substring(
          0,
          this.form.formul.length - 1
        );
        return;
      }
      this.form.formul = this.form.formul + val;
      this.$refs.formulRef.focus();
    },
    // 选择游戏
    selectType(e) {
      this.qufuPeizhi = [];
      this.gameListAll.forEach((r) => {
        if (r.id == e) {
          this.form.gameName = r.name;
          this.form.gameType = r.type;
        }
      });
      let params = {};
      params.gameId = this.form.gameId;
      this.selectEquas = [];
      this.attrNumber = [];
      this.attrRadio = [];
      this.attrCheckbox = [];
      this.attrBoxradio = [];
      getAppEquationList(params).then((res) => {
        if (res.data && res.data.length) {
          res.data.forEach((r) => {
            if (
              (r.fieldType == "number" ||
                r.fieldType == "radio" ||
                r.fieldType == "checkbox" ||
                r.fieldType == "boxradio") &&
              r.isEnable === "0"
            ) {
              if (r.fieldType == "number") {
                this.attrNumber.push(r);
              } else if (r.fieldType == "radio") {
                this.attrRadio.push(r);
              } else if (r.fieldType == "checkbox") {
                this.attrCheckbox.push(r);
              } else if (r.fieldType == "boxradio") {
                this.attrBoxradio.push(r);
              }
              this.selectEquas.push(r);
            }
          });
        }
      });
      this.getSystem(e);
    },
    async getSystem(e) {
      if (this.form.gameType == 1) {
        // 端游
        // 大区
        const resss = await gameDictionaryApi.getChildList({
          gameId: e,
          systemKey: "group",
        });
        this.groupList = resss.rows;
      } else {
        // 系统
        const res = await gameDictionaryApi.getChildList({
          gameId: e,
          systemKey: "system",
        });
        this.systemList = res.rows;
        //运营商
        const ress = await gameDictionaryApi.getChildList({
          gameId: e,
          systemKey: "carrier",
        });
        this.carrierList = ress.rows;
      }
    },

    // 系统选择改变
    changeSystem(e, row) {
      this.systemList.forEach((r) => {
        if (r.fieldName == e) {
          row.systemId = r.id;
        }
      });
    },
    // 运营商改变  获取大区列表
    getAreaList(e, row) {
      let obj = {
        gameId: this.form.gameId,
        systemKey: "group",
      };
      row.groupName = "";
      row.groupId = "";
      row.serverName = "";
      row.serverId = "";
      // 运营商改变 找出选择的运营商的对象
      if (e) {
        this.carrierList.forEach((r) => {
          if (r.fieldName == e) {
            obj.systemKey = r.systemKey + "group";
            row.carrierId = r.id;
          }
        });
      } else {
        row.carrierId = "";
      }
      gameDictionaryApi.getChildList(obj).then((res) => {
        this.groupList = res.rows;
      });
    },
    // 大区选择改变
    async changefn(e, row) {
      row.serverName = "";
      row.serverId = "";
      this.groupList.forEach((r) => {
        if (r.fieldName == e) {
          row.groupId = r.id;
        }
      });
      const resss = await gameDictionaryApi.getList({ parentId: row.groupId });
      this.serverList = resss.rows;
    },

    // 服务器选择
    changeServe(e, row) {
      this.serverList.forEach((r) => {
        if (r.fieldName == e) {
          row.serverId = r.id;
        }
      });
    },
    // chgangeServe(e) {
    //   let obj = this.serverList.find((item) => item.id === e);
    //   this.form.formul = this.form.formul + obj.fieldName;
    // },
    // chgangeServee(e) {
    //   console.log(e);
    //   let obj = this.serverList.find((item) => item.id === e);
    //   console.log("111111", obj);
    //   this.youxishuname = obj.fieldName;
    // },
    /** 查询公式配置列表 */
    getList() {
      this.loading = true;
      tenantFormulaSettingsList(this.queryParams).then((response) => {
        this.equationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map((item) => item.id);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加公式配置";
      this.form = {
        formul: "",
        name: "",
        gameId: "",
        gameName: "",
        serverRegion: "",
        remark: "",
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.title = "修改公式配置";
      this.form = { ...row };
      if (this.form.serverRegion && this.form.serverRegion != "[]") {
        this.qufuPeizhi = JSON.parse(this.form.serverRegion);
      }
      this.selectEquas = [];
      this.attrNumber = [];
      this.attrRadio = [];
      this.attrCheckbox = [];
      this.attrBoxradio = [];
      getAppEquationList({ gameId: this.form.gameId }).then((res) => {
        if (res.data && res.data.length) {
          res.data.forEach((r) => {
            if (
              (r.fieldType == "number" ||
                r.fieldType == "radio" ||
                r.fieldType == "checkbox" ||
                r.fieldType == "boxradio") &&
              r.isEnable === "0"
            ) {
              if (r.fieldType == "number") {
                this.attrNumber.push(r);
              } else if (r.fieldType == "radio") {
                this.attrRadio.push(r);
              } else if (r.fieldType == "checkbox") {
                this.attrCheckbox.push(r);
              } else if (r.fieldType == "boxradio") {
                this.attrBoxradio.push(r);
              }
              this.selectEquas.push(r);
            }
          });
        }
      });
      this.getSystem(this.form.gameId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.serverRegion = ''
          if(this.qufuPeizhi&&this.qufuPeizhi.length){
            this.form.serverRegion = JSON.stringify(this.qufuPeizhi);
          }
          
          if (this.form.id != null) {
            tenantFormulaSettingsEdit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            tenantFormulaSettingsAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除公式配置编号为"' + ids + '"的数据项？')
        .then(function () {
          return tenantFormulaSettingsDel(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.type_box {
  border: 1px solid #ccc;
  // background: #f7f7f7;
  border-radius: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  // padding: 10px;
  .attrhead {
    font-weight: bold;
    background: #f7f7f7;
    padding-left: 20px;
  }
  .kexuan-box {
    flex-wrap: wrap;
    padding: 10px;
    .attr_item {
      line-height: 30px;
      border: 1px solid #ccc;
      padding: 0 10px;
      border-radius: 5px;
      margin-right: 10px;
      margin-bottom: 10px;
      cursor: pointer;
    }
  }
}
.tip{
  line-height: 22px;
  margin-bottom: 10px;
}
.qufu_box {
  width: 840px;
  border: 1px solid #ccc;
  padding-bottom: 10px;
  .head {
    color: #000;
    font-weight: bold;
    background-color: #f7f7f7;
    margin-bottom: 10px;
    .tit {
      width: 100%;
      text-align: center;
    }
  }
  .qufu_item {
    padding: 0 15px;
    margin-bottom: 10px;
    .el-select {
      margin-right: 10px;
    }
    .move {
      width: 70px;
      flex-shrink: 0;
      text-align: center;
      // margin-left: 10px;
      font-size: 20px;
      .el-icon-error {
        cursor: pointer;
      }
    }
  }
  .add_btn {
    margin-top: 10px;
    text-align: center;
  }
}

::v-deep .gongshi_form .el-form-item__content {
  max-width: calc(100% - 100px);
}
</style>